<!-- 库存管理->库存期初 -->
<template>
  <div class="content-wrapper a-base-container">
    <div class="requisition-set-wrapper">
      <!-- 按钮 -->
      <div class="btn-wrapper clearfix">
        <a-row class="text-center clearfix">
          <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
            <a-col
              v-if="permissions.includes('inventoryBalance:save')"
              :class="editMask == false ? '' : 'btns-disable'"
              :xs="btn_grid.xs"
              :sm="btn_grid.sm"
              :md="btn_grid.md"
              :lg="btn_grid.lg"
              :xl="btn_grid.xl"
            >
              <div
                class="btns"
                @click="editMask == false ? submitServer() : ''"
              >
                <a-icon class="btns-icon" type="save" />
                <div class="btns-text">保存</div>
              </div>
            </a-col>

            <a-col
              :class="voucherState == -1 && editMask ? '' : 'btns-disable'"
              :xs="btn_grid.xs"
              :sm="btn_grid.sm"
              :md="btn_grid.md"
              :lg="btn_grid.lg"
              :xl="btn_grid.xl"
            >
              <div
                class="btns"
                @click="voucherState == -1 && editMask ? clickEdit() : ''"
              >
                <a-icon class="btns-icon" type="edit" />
                <div class="btns-text">修改</div>
              </div>
            </a-col>

            <a-col
              :class="voucherState >= 1 || !editMask ? 'btns-disable' : ''"
              :xs="btn_grid.xs"
              :sm="btn_grid.sm"
              :md="btn_grid.md"
              :lg="btn_grid.lg"
              :xl="btn_grid.xl"
            >
              <a-dropdown class="btns" key="submit" style="display: block">
                <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                  <a-icon class="btns-icon" type="check-circle" />
                  <div class="btns-text">
                    提交
                    <a-icon type="down" style="vertical-align: middle" />
                  </div>
                </a>
                <a-menu slot="overlay">
                  <a-menu-item key="0">
                    <a
                      href="javascript:void(0)"
                      @click="
                        voucherState == -1 && editMask ? submitOrder(0) : ''
                      "
                    >
                      <span
                        :class="
                          voucherState == -1 && editMask ? '' : 'color-gray'
                        "
                        >提交</span
                      >
                    </a>
                  </a-menu-item>
                  <a-menu-item key="1">
                    <a
                      href="javascript:void(0)"
                      @click="voucherState == 0 ? submitOrder(-1) : ''"
                    >
                      <span :class="voucherState == 0 ? '' : 'color-gray'"
                        >撤回提交</span
                      >
                    </a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </a-col>

            <a-col
              v-if="permissions.includes('inventoryBalance:delete')"
              :class="orderId && voucherState == -1 ? '' : 'btns-disable'"
              :xs="btn_grid.xs"
              :sm="btn_grid.sm"
              :md="btn_grid.md"
              :lg="btn_grid.lg"
              :xl="btn_grid.xl"
            >
              <div
                class="btns"
                @click="orderId && voucherState == -1 ? deleteOrder() : ''"
              >
                <a-icon class="btns-icon" type="delete" />
                <div class="btns-text">删除</div>
              </div>
            </a-col>
            <a-col
              v-if="permissions.includes('inventoryBalance:examine')"
              :class="voucherState == 0 && orderId ? '' : 'btns-disable'"
              :xs="btn_grid.xs"
              :sm="btn_grid.sm"
              :md="btn_grid.md"
              :lg="btn_grid.lg"
              :xl="btn_grid.xl"
            >
              <div
                class="btns"
                @click="voucherState == 0 && orderId ? auditClick(1) : ''"
              >
                <a-icon class="btns-icon" type="audit" />
                <div class="btns-text">审核</div>
              </div>
            </a-col>
            <a-col
              v-if="permissions.includes('inventoryBalance:examine')"
              :class="voucherState == 2 && orderId ? '' : 'btns-disable'"
              :xs="btn_grid.xs"
              :sm="btn_grid.sm"
              :md="btn_grid.md"
              :lg="btn_grid.lg"
              :xl="btn_grid.xl"
            >
              <div
                class="btns"
                @click="voucherState == 2 && orderId ? auditClick(0) : ''"
              >
                <a-icon class="btns-icon" type="audit" />
                <div class="btns-text">弃审</div>
              </div>
            </a-col>
            <a-col
              :xs="btn_grid.xs"
              :sm="btn_grid.sm"
              :md="btn_grid.md"
              :lg="btn_grid.lg"
              :xl="btn_grid.xl"
            >
              <div class="btns" @click="importDataFun">
                <a-icon class="btns-icon" type="import" />
                <div class="btns-text">导入</div>
              </div>
            </a-col>
            <a-col
              :xs="btn_grid.xs"
              :sm="btn_grid.sm"
              :md="btn_grid.md"
              :lg="btn_grid.lg"
              :xl="btn_grid.xl"
            >
              <div class="btns" @click="exportDataFun">
                <a-icon class="btns-icon" type="export" />
                <div class="btns-text">导出</div>
              </div>
            </a-col>
          </a-col>
        </a-row>
      </div>
      <div
        ref="print"
        class="documents-wrapper"
        id="documents-wrapper"
        v-show="showModel"
      >
        <h3 class="text-center">库存期初结存</h3>
        <div>
          <span class="audit-status" v-show="voucherState == 2">已审核</span>
          <span class="audit-status" v-show="voucherState == 0">待审核</span>
          <!-- <span class="audit-status" v-show="voucherState==1 || voucherState==10">{{voucherState==1?'已审核':'关闭'}}</span> -->
        </div>

        <a-form-model :layout="formLayout">
          <div class="header-box">
            <order-dynamic-form
              :FormData="orderHeaderData"
              @changetime="onChangeTime"
              @clickItem="setValue"
            ></order-dynamic-form>
          </div>
          <div class="table-box">
            <div class="edit-mask" v-show="editMask">
              <!-- 遮罩（点击修改关闭遮罩） -->
            </div>

            <a-table
              id="bills_tb"
              :columns="columns"
              :data-source="dataSource"
              :customRow="customClick"
              :scroll="{ x: 1000, y: 347 }"
              :pagination="false"
              @change="onTableChange"
              :size="small"
              ref="scrollTable"
              bordered
              v-loadmore="loadMore"
            >
              <template
                v-if="isRouterAlive"
                slot="number"
                slot-scope="text, record, index"
              >
                <div v-if="index == dataSource.length - 1">合计</div>
                <div v-else>
                  {{ index + 1 }}
                </div>
              </template>
              <template
                v-for="col in slotArray"
                :slot="col"
                slot-scope="text, record, index"
              >
                <div data-key="" v-if="isRouterAlive">
                  <div v-if="col == 'warehouseName'">
                    <div
                      @click="setWhereHouseName(record, index)"
                      style="width: 100%; height: 26px; display: block"
                    >
                      {{ record.warehouseName }}
                    </div>
                  </div>
                  <editable-cell
                    v-else
                    :text="text"
                    :col="col"
                    :index="index"
                    :record="record"
                    :dataSource="dataSource"
                    :unitsDataDetails="unitsDataDetails"
                    :unitsAssistSelect="unitsAssistSelect"
                    :dynamicAllData="dynamicFormData"
                    :dynamicFormDataMap="dynamicFormDataMap"
                    @choiceAddData="choiceAddData(index, $event)"
                    @change="onCellChange(index, col, $event)"
                    @newAddData="handleAdd"
                    :showTotal="showTotal"
                  />
                </div>
              </template>
            </a-table>
          </div>
          <div class="footer-box">
            <order-dynamic-form
              :FormData="orderFooterData"
              @changetime="onChangeTime"
              @clickItem="setValue"
            ></order-dynamic-form>
          </div>
        </a-form-model>
      </div>
      <div class="contextmenu-box">
        <!-- 右键菜单 -->
        <ul
          v-show="visible"
          :style="{ left: left + 'px', top: top + 'px' }"
          class="contextmenu"
        >
          <li @click="handleAdd()">新增行</li>
          <li @click="handleDelete()">删除行</li>
        </ul>
      </div>
      <drawerBox
        ref="searchList"
        :unitData="unitData"
        :unitsData="unitsData"
        :unitsDataDetails="unitsDataDetails"
        @editClickOrder="editClickOrder"
      ></drawerBox>
    </div>

    <!--加载中-->
    <div class="loading-wrapper" v-show="loading">
      <a-spin class="loading-content" tip="加载中..." />
    </div>
    <!--用做横向打印-->
    <!-- <div v-html="stylePrint"></div> -->
    <print-modal
      ref="printDom"
      v-if="printVisible"
      :incomingPrintData="incomingPrintData"
      @cancelPrint="cancelPrint"
    ></print-modal>

    <importAndExport ref="importRef" @syncFun="syncFun"></importAndExport>
  </div>
</template>
<script>
import { mapState } from "vuex";
import {
  save,
  examine,
  remove,
  getCode,
  submitOrder
} from "@/api/inventory/inout";
import { getAction, postAction } from "@/api/manage";
import importAndExport from "@/components/ImportAndExport/initialInventory";

import pro from "@/mixins/procurement/pro";
export default {
  mixins: [pro],
  components: {
    importAndExport
  },
  data() {
    return {
      sourceCode: "PeriodStartOfStock",
      warehouseId: null,
      warehouseName: null,
      showTotal: false,
      voucherState: -1,

      receiveDeliverType: 1, //1入，2出
      pageData: [], // 分页后的数据
      currentPage: 1 // 当前页码
    };
  },
  created() {
    this.initForm(1);
    setTimeout(() => {
      this.getList();
    }, 600);
  },

  computed: {
    ...mapState({
      userInfo: state => state.user.info,
      permissions: state => state.user.permissions
    })
  },

  methods: {
    /** 将数组进行分页，返回新的分页数组
     * @param {Object} pageSize 每页大小
     * @param {Object} arr 数组
     */
    returnAllPageFunc(pageSize, arr) {
      let pageNum = 1;
      let pageObj = {
        pageNum: 1,
        list: []
      };
      let pageResult = [];

      let newArr = JSON.parse(JSON.stringify(arr));
      let totalPage = newArr.length ? Math.ceil(arr.length / pageSize) : 0; // 计算总页数

      for (let i = 1; i <= totalPage; i++) {
        if (totalPage == 1) {
          pageNum += 1;
          pageObj.list = newArr.splice(0, arr.length);
        } else if (i <= totalPage) {
          pageNum += 1;
          pageObj.list = newArr.splice(0, pageSize);
        } else {
          pageObj.list = newArr.splice(0, arr.length % pageSize);
        }
        pageResult.push(pageObj);
        pageObj = {
          pageNum: pageNum,
          list: []
        };
      }
      return pageResult;
    },

    //表格滚动条事件，下滑加载更多
    loadMore(e) {
      if (e == "down") {
        console.log("滚动条到达底部");
        this.currentPage += 1;
        this.dataSource = this.dataSource.concat(
          this.pageData[this.currentPage - 1].list
        );
      } else {
        console.log("滚动条到达顶部");
      }
    },
    //滚动事件
    handleScroll() {},

    //新增
    newForecast() {
      this.showModel = "order";
      this.editMask = false;
      this.loading = false;
      this.voucherState = -1;
      this.sourceVoucherData = {}; //清空来源数据
      this.initForm(1);
    },
    //获取列表
    getList() {
      let formData = this.dynamicFormDataMap.get("warehouseId_表头");
      this.warehouseId = formData.valueId;
      this.warehouseName = formData.valueName;
      this.$store.commit("SET_WHEREHOUSEID", this.warehouseId);
      // console.log(this.orderHeaderData)
      // this.orderHeaderData.forEach(element => {
      //     if (element.code == 'warehouseId') {
      //         console.log(element)
      //         this.warehouseId = element.valueId;
      //         this.warehouseName = element.valueName;
      //     }
      // });
      getAction("/inOut/recordMain/getByWarehouseId", {
        warehouseId: this.warehouseId
      })
        .then(response => {
          if (response.code === 200) {
            let data = response.data;

            if (data == null) {
              this.voucherState = -1;
              // this.dataSource = [{
              //     warehouseId: this.warehouseId,
              //     warehouseName: this.warehouseName,
              // }];
              this.dataSource = [];
              //补足表格
              if (
                this.dataSource.length < this.dataSourceNumber ||
                this.dataSource.length == 0
              ) {
                for (
                  let i = this.dataSource.length;
                  i < this.dataSourceNumber;
                  i++
                ) {
                  let array = {
                    number: i + 1
                  };
                  this.dataSource.push(array);
                }
                this.addTotal(); //添加合计
              } else {
                for (let i = 0; i < 2; i++) {
                  let array = {
                    number: i + 1
                  };
                  this.dataSource.push(array);
                }
                this.addTotal(); //添加合计
              }
              this.reload();

              this.editMask = true;
              this.loading = false;
              this.voucherState = -1;
            }

            if (data.orderDetailList.length > 0) {
              this.currentPage = 1; // 设置页码初始为1
              this.pageData = []; // 清空原分页数据
              this.dataSource = []; // 清空源数据
              let dataList = data.orderDetailList;
              this.pageData = this.returnAllPageFunc(20, dataList); // 将获取到的数据分页处理，每页显示20条
              this.dataSource = this.pageData[this.currentPage - 1].list; // 默认取第一页的数据
              this.orderId = data.id;
              this.voucherState = data.voucherState;
              // if (this.voucherState == 1) {
              this.editMask = true;
              // }

              //补足表格
              if (
                this.dataSource.length < this.dataSourceNumber ||
                this.dataSource.length == 0
              ) {
                for (
                  let i = this.dataSource.length;
                  i < this.dataSourceNumber;
                  i++
                ) {
                  let array = {
                    number: i + 1
                  };
                  this.dataSource.push(array);
                }
                this.addTotal(); //添加合计
              } else {
                // for (let i = 0; i < 2; i++) {
                //   let array = {
                //     number: i + 1,
                //   };
                //   this.dataSource.push(array);
                // }
                // this.addTotal(); //添加合计
              }
              for (let i = 0; i < this.dataSource.length; i++) {
                if (this.dataSource[i].unitId) {
                  //单计量
                  // this.unitData.forEach(item => {
                  //     if (item.id == this.dataSource[i].unitId) {
                  //         this.dataSource[i].baseUnit = item.name;
                  //         this.dataSource[i].baseUnit_temp_id = item.id;//单计量id
                  //         this.dataSource[i].unitId = item.id;
                  //     }
                  // })
                  this.dataSource[i].baseUnit_temp_id = this.dataSource[
                    i
                  ].unitId;
                  this.dataSource[i].baseUnit = this.dataSource[i].baseUnitName;
                }

                if (this.dataSource[i].unitGroupId) {
                  //多计量
                  // this.unitsDataDetails.forEach(item => {
                  //     if (item.id == this.dataSource[i].unitGroupId) {
                  //         this.dataSource[i].baseUnit = item.name;
                  //         this.dataSource[i].baseUnit_temp_id = item.id;//多计量
                  //         this.dataSource[i].unitGroupId = item.id;
                  //     }
                  // })
                  this.dataSource[i].baseUnit_temp_id = this.dataSource[
                    i
                  ].unitGroupId; //多计量
                  this.dataSource[i].baseUnit = this.dataSource[i].baseUnitName;

                  //辅助计量数据
                  this.unitsAssistSelect = this.returnGroupUnits(
                    this.dataSource[i].unitGroupId
                  );
                  //辅助计量修改时设值
                  this.unitsAssistSelect.forEach(item => {
                    if (item.id == this.dataSource[i].subUnit) {
                      this.dataSource[i].subUnit = item.name;
                      this.dataSource[i].subUnit_temp_id = item.id;
                    }
                  });
                }
              }
              for (let i = 0; i < this.orderFooterData.length; i++) {
                for (const key in data) {
                  if (this.orderFooterData[i].columnType == "搜索选择") {
                    if (this.orderFooterData[i].code.indexOf("Id") != "-1") {
                      let tempname =
                        this.orderFooterData[i].code.substring(
                          0,
                          this.orderFooterData[i].code.length - 2
                        ) + "Name";
                      this.$set(this.orderFooterData[i], "valueId", data[key]);
                      this.$set(
                        this.orderFooterData[i],
                        "valueName",
                        data[tempname]
                      );
                      this.$set(
                        this.orderFooterData[i],
                        "value",
                        data[tempname]
                      );
                    }
                  } else {
                    if (key == this.orderFooterData[i].code) {
                      this.$set(this.orderFooterData[i], "value", data[key]);
                    }
                  }
                }
              }
              this.reload();
            } else {
              this.editMask = true;
              this.loading = false;
              this.voucherState = -1;
            }
          }
        })
        .catch(error => {});
    },
    setWhereHouseName(record, index) {
      if (record.number != "合计") {
        this.dataSource.forEach((item, i) => {
          if (index == i) {
            item.warehouseId = this.warehouseId;
            item.warehouseName = this.warehouseName;
          }
        });
        this.reload();
      }
    },
    //保存
    submit(requestData) {
      const ids = requestData.orderDetailList.map(item => item.inventoryId);
      const idsSet = new Set(ids);
      if (idsSet.size == ids.length) {
        console.log("不存在同个值");
        this.isSaveRun = true;
      } else {
        console.log("存在同个值");
        this.$message.warning("库存期初设置不允许出现相同的物料！");
        this.isSaveRun = true;
        return;
      }
      save(requestData)
        .then(response => {
          this.isSaveRun = true;
          if (response.code === 200) {
            this.$message.success("保存成功");
            this.getList();
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(e => {
          this.isSaveRun = true;
        });
    },
    //单据提交
    submitOrder(type) {
      let data = {
        id: this.orderId,
        status: type //状态 -1:撤回提交,0:提交
      };
      console.log(this.orderId);
      if (!this.orderId) {
        this.$message.warning("该单据未保存不需要提交");
        return;
      }
      if (this.voucherState == -1 && type == -1) {
        this.$message.warning("该单据未提交无需撤回提交");
        return;
      }
      submitOrder(data).then(res => {
        if (res.code === 200) {
          if (type == 0) {
            this.$message.success("提交成功");
          } else {
            this.$message.success("撤回提交成功");
          }
          this.getIdByData();
        }
      });
    },
    setValue(data) {
      const { orderHeaderData } = this;
      this.orderId = null;
      for (let i = 0; i < orderHeaderData.length; i++) {
        if (orderHeaderData[i].code == data.codesName) {
          this.$set(orderHeaderData[i], "value", data.name);
          this.$set(orderHeaderData[i], "valueId", data.id);
          this.$set(orderHeaderData[i], "valueName", data.name);
          this.warehouseId = data.id;
          this.warehouseName = data.name;
          break;
        }
      }
      Object.assign(this.orderHeaderData, orderHeaderData);

      this.getList();
    },
    //审核
    auditClick(type) {
      let requestData = {
        id: this.orderId,
        status: type
      };
      examine(requestData).then(response => {
        if (response.code === 200) {
          const backData = response.data;
          if (type == 1) {
            this.$message.success("审核成功");
            this.editMask = true;
            this.orderId = null;
            this.getList();
          }
          if (type == 0) {
            this.$message.success("弃审成功");
            this.editMask = true;
            this.orderId = null;
            this.getList();
          }
        } else {
          // this.$message.warning(response.message);
        }
      });
    },
    //删除
    remove(postData) {
      remove(postData).then(response => {
        if (response.code === 200) {
          this.$message.success("删除成功");
          this.orderId = "";
          this.voucherState = -1;
          this.getList(); //获取最新一条数据
        } else {
          this.$message.error(response.message);
        }
      });
    },
    //获取单据编号
    getCode() {
      let data = {
        sourceCode: this.sourceCode
      };
      getCode(data).then(res => {
        if (res.code == 200) {
          this.receiptNumber = res.message;
          for (let i = 0; i < this.orderHeaderData.length; i++) {
            if (this.orderHeaderData[i].code == "voucherCode") {
              this.$set(this.orderHeaderData[i], "onEdit", false);
              this.$set(this.orderHeaderData[i], "value", this.receiptNumber);
            }
          }
        } else {
          // this.$message.warning(res.message);
        }
      });
    },
    importDataFun() {
      //导入数据
      this.$refs.importRef.importFile();
    },
    exportDataFun() {
      //导出数据
      this.$refs.importRef.exportCrmData();
    }
  }
};
</script>
<style lang="less">
@import "~@/style/purchase/voucher.less";
</style>
